//
//  OAuthViewController.swift
//  DSWB-SB
//
//  Created by YouYQ on 2020/8/30.
//  Copyright © 2020 YouYQ. All rights reserved.
//

import UIKit
import WebKit

class OAuthViewController: UIViewController {
    var webView : WKWebView!
    override func viewDidLoad() {
        super.viewDidLoad()
        setupNaviBar()
        configWebView()
        loadPage()
    }
    deinit {
        print("deinit")
    }
}
extension OAuthViewController {
    func setupNaviBar() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .plain, target: self, action: #selector(closeAction))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "填充", style: .plain, target: self, action: #selector(fillAction))
        navigationItem.title = "授权界面"
    }
    func configWebView() {
        let config = WKWebViewConfiguration()
        config.preferences.minimumFontSize = 10.0
        config.userContentController.add(self, name: "playSound")
        webView = WKWebView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height), configuration: config)
        view.addSubview(webView)
        webView.navigationDelegate = self
        webView.uiDelegate = self
    }
    
    func loadPage() {
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(sina_AppKey)&redirect_uri=\(sina_RedirectUri)"
        guard let url = URL(string: urlString) else {
            return
        }
        print(url)
        let request = URLRequest(url: url)
        webView.load(request)
        
    }
}

extension OAuthViewController: WKNavigationDelegate {
    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        print("didStartProvisionalNavigation")
        HUD.show(.progress)
    }
    func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
        print("didFailProvisionalNavigation")
        //无网络的时候
        HUD.hide()
    }
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        print("didFinish")
        //地址错误(参数错误)和加载完成
        HUD.hide()
    }
    func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
        print("didFail")
        //
        HUD.hide()
    }
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
//        guard let url = navigationAction.request.url else {
//            decisionHandler(.allow)
//           return
//        }
//        let urlString = url.absoluteString
//
//        guard urlString.contains("code=") else {
//            decisionHandler(.allow)
//            return
//        }
//        guard var code = urlString.components(separatedBy: "code=").last else {
//            return
//        }
        let code = "497e75c3e75f87c740f1e915d67eaafe"
        //拿code换accessToken
        loadAccessToken(code: code)
        
        decisionHandler(.cancel)
    }
}

//MARK:- 请求数据
extension OAuthViewController {
    //获取Token
    //获取Token
    func loadAccessToken(code: String) {
        NT.loadUserInfo(urlString: API.loadUserInfo) { data in
            print(data)
        }
    }
//    func loadAccessToken(code: String) {
//        NetworkTools.shareInstance.loadAccessToken(code: code) { (data: [String : Any]?, error: Error?) in
//            guard let dict = data else {
//                return
//            }
//            let userInfo = UserAccount(dict: dict)
//
//            userInfo.expires_in = (dict["expires_in"] as? TimeInterval)!
//            self.loadUserInfo(userInfo: userInfo)
//        }
//    }
    //获取用户信息
//    func loadUserInfo(userInfo : UserAccount) {
//        guard let accessToken = userInfo.access_token else {
//            return
//        }
//        guard let uid = userInfo.uid else {
//            return
//        }
//
//        NetworkTools.shareInstance.loadUserInfo(accessToken: accessToken, uid: uid) { (data: [String : Any]?, error: Error?) in
//            guard let resultDic = data else {
//                return
//            }
//
//            userInfo.screen_name = resultDic["screen_name"] as? String
//            userInfo.avatar_large = resultDic["avatar_hd"] as? String
//            print("加载用户之后")
//            print(userInfo)
//            //归档
////            var homeDocment = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
////            homeDocment = (homeDocment as NSString).appendingPathComponent("account.plist")
////            print(homeDocment)
//            /*
//            do {
//                try NSKeyedArchiver.archivedData(withRootObject: userInfo, requiringSecureCoding: true)
//            }catch {
//                print(error)
//            }
// */
//
//            guard let data = try? NSKeyedArchiver.archivedData(withRootObject: userInfo, requiringSecureCoding: true) else {
//                return
//            }
//            guard let _ = try? data.write(to: URL(fileURLWithPath: UserAccountViewModel.shareInstance.sanboxPath)) else {
//                return
//            }
//            //给单例对象赋值
//            UserAccountViewModel.shareInstance.account = userInfo
//            //try! NSKeyedArchiver.archivedData(withRootObject: userInfo, requiringSecureCoding: true)
//            //显示欢迎界面
//            self.dismiss(animated: false) {
//                UIApplication.shared.keyWindow?.rootViewController = WelcomeViewController()
//            }
//        }
//    }
}

extension OAuthViewController: WKUIDelegate {
    
}

extension OAuthViewController : WKScriptMessageHandler {
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        if message.name == "playSound" {
            print("js调用OC")
        }
    }
}

extension OAuthViewController {
    @objc private func closeAction() {
        dismiss(animated: true, completion: nil)
    }
    @objc private func fillAction() {
        print("fill")
        let jsCode = "document.getElementById('loginName').value='17310390815';document.getElementById('loginPassword').value='qwer1234'"
        webView.evaluateJavaScript(jsCode) { (result, error) in
        }
    }
}
